//
//  RegistrationTextCell.swift
//  PorscheRegistration
//
//  Created by Jinzhu Liu on 2023/11/16.
//

import UIKit
import Combine

class RegistrationTextCell: RegistrationBaseCell {
    
    var textViewModel: RegistrationTextFieldCellViewModelType? {
        return (viewModel as? RegistrationTextFieldCellViewModelType)
    }
    var textField: UITextField
    
    private var cancelable = Set<AnyCancellable>()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        self.textField = UITextField()
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }
    
    override func setupUI() {
        super.setupUI()
        textField.delegate = self
        textField.borderStyle = .roundedRect
        textField.textAlignment = .right
        self.contentView.addSubview(textField)
        textField.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            textField.heightAnchor.constraint(equalToConstant: 32.0),
            textField.leadingAnchor.constraint(equalTo: titleLabel.trailingAnchor, constant: 10.0),
            textField.trailingAnchor.constraint(equalTo: self.contentView.safeAreaLayoutGuide.trailingAnchor, constant: -16.0),
            textField.centerYAnchor.constraint(equalTo: titleLabel.centerYAnchor),
        ])
    }
    
    override func update(with viewModel: AnyObject?) {
        super.update(with: viewModel)
        guard let textOutputViewModel = viewModel as? RegistrationTextFieldCellViewModelOutputType else { return }
        textField.text = textOutputViewModel.textValue
        textField.isUserInteractionEnabled = textOutputViewModel.textFieldEnable
        
        cancelable.forEach { cancellableItem in
            cancellableItem.cancel()
        }
        cancelable.removeAll()
        
        textOutputViewModel.textValuePublisher.sink { [unowned self] textValue in
            textField.text = textValue
        }.store(in: &cancelable)
    }
    
}

extension RegistrationTextCell: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        guard var textViewModel else { return }
        textViewModel.textValue = textField.text ?? ""
    }
}
